package YunNotes.servlet;

import YunNotes.allnotes.control.NoteAction;
import YunNotes.util.json.GetJson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;

/**
 * @author Hzheng
 * @date 2020-06-03 21:22
 */
@WebServlet(name = "PraiseServlet")
public class PraiseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //给前端输出
        PrintWriter out = response.getWriter();
        out.println("前端的请求方法是：" + request.getMethod());

        //获取num的值
        String s1 = request.getParameter("num");
        int num = Integer.parseInt(s1);

        NoteAction noteAction = new NoteAction();
        try {
            out.println(noteAction.queryPoints(num));
            out.println("序号：" + num + "的点赞量为：" + noteAction.queryPoints(num));
        } catch (SQLException e) {
            out.println("查询失败！");
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //给前端输出
        PrintWriter out = response.getWriter();
        out.println("前端的请求方法是：" + request.getMethod());

        //接收前端数据
        InputStreamReader insr = new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8);
        StringBuilder result = new StringBuilder();
        int respInt = insr.read();
        while (respInt != -1) {
            // 读取请求数据
            result.append((char) respInt);
            respInt = insr.read();
        }
        System.out.println("前端传递的数据为:" + result);
        insr.close();
        String data = result.toString();

        //获取id和num的值
        GetJson getJson = new GetJson();
        String s = getJson.Get(data, "id");
        int id = Integer.parseInt(s);
        String s1 = getJson.Get(data, "num");
        int num = Integer.parseInt(s1);

        NoteAction noteAction = new NoteAction();
        try {
            noteAction.praise(num, id);
            out.println("点赞或取消赞成功！");
            out.println(noteAction.queryPoints(num));
        } catch (SQLException e) {
            out.println("点赞或取消赞失败！");
            e.printStackTrace();
        }
    }
}
